package com.example.yamba;

import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.models.ErrorInfo;
import com.sina.weibo.sdk.openapi.models.Status;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.widget.Toast;

import org.json.*;
public class UpdateService extends Service {
	private static final String TAG = UpdateService.class.getSimpleName();
	private static final int delay = 6000;
	private boolean runFlag = false;
	private Updater updater;
	private MyStatusesAPI statusesAPI ;
	private DBHepler dbHelper;
	private SQLiteDatabase db;
	private YambaApplication yamba;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		updater = new Updater();
		statusesAPI = ((YambaApplication)getApplication()).getStatusesAPI();
		dbHelper = new DBHepler(this);
		yamba = (YambaApplication)getApplication();
		Log.i(TAG,"OnCreated");
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		runFlag = false;
		updater.interrupt();
		updater = null; 
		Log.i(TAG,"OnDestroy");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.i(TAG,"Onstarted");
		runFlag = true;
		yamba.setIsRunning(runFlag);
		updater.start();
		return super.onStartCommand(intent, flags, startId);
	}
	
	private class Updater extends Thread{
		JSONArray jsonArray ;
		String strList ;
		public Updater(){
			super("UpdateService_Thread");
		}
		public void run(){
			UpdateService service = UpdateService.this;
			while(service.runFlag){
				Log.i(TAG,"Thread running ");
				try{
					YambaApplication application = (YambaApplication)service.getApplication();
					int newStatus = application.fetchStatusUpdate();
					if(newStatus>0) {
						Log.i(TAG, "we have " + newStatus + " status");
						Intent intent = new Intent("com.example.yamba.NEW_STATUS");
						intent.putExtra("com.example.yamba.NEW_STATUS_COUNT",newStatus);
						sendBroadcast(intent);
					}
					Thread.sleep(delay);
				}catch(InterruptedException e){
					service.runFlag = false;
					yamba.setIsRunning(false);
					Log.d(TAG,"Thread interrupted");
				}

			}
		}

	}
}
